package com.dongjiantong.web.protal.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.dongjiantong.common.exceptions.HttpCode;
import com.dongjiantong.common.exceptions.OPServerException;
import com.dongjiantong.common.model.Response;
import com.dongjiantong.common.redis.RedisUtil;
import com.dongjiantong.farmrecords.enums.FarmRecordsDicGroupEnum;
import com.dongjiantong.farmrecords.enums.FarmRecordsNumberStatus;
import com.dongjiantong.openplatform.annotations.OpenBean;
import com.dongjiantong.openplatform.annotations.OpenMethod;
import com.dongjiantong.sys.enums.AnimalTypeEnum;
import com.dongjiantong.sys.model.AnimalType;
import com.dongjiantong.sys.model.DicData;
import com.dongjiantong.sys.model.SysLabelModel;
import com.dongjiantong.sys.service.AnimalTypeService;
import com.dongjiantong.sys.service.DicDataService;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.curator.shaded.com.google.common.collect.Maps;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 基础信息
 *
 * @author cao
 * @create 2017-11-25 下午4:36
 **/

//@RestController
//@RequestMapping("/api/web/sys")
@Slf4j
@OpenBean
public class SysController {

    @Reference(version = "1.0.3")
    public AnimalTypeService animalTypeService;
    @Reference(version = "1.0.0")
    public DicDataService dicDataService;

    @OpenMethod(
            key = "web.sys.animalType",
            paramNames = {"level", "pId"},
            httpMethods = RequestMethod.GET
    )
    public Response<List<AnimalType>> animalType(Integer level, Long pId) {

        if (level == 1) {
            return Response.ok(animalTypeService.queryOneLevel());
        } else if (level == 2) {
            return Response.ok(animalTypeService.queryTwoLevel(pId));
        } else if (level == 3) {
            return Response.ok(animalTypeService.queryThreeLevel(pId));
        }

        return Response.ok(animalTypeService.queryOneLevel());

    }

    @OpenMethod(
            key = "web.sys.animalType.tree",
            paramNames = {},
            httpMethods = RequestMethod.GET
    )
    public Response<List<Object>> animalTypeWithTree() {

        return Response.ok(treeNode(0L));

    }

    private List<Object> treeNode(long pid) {
        List<AnimalType> childTreeNodes = animalTypeService.queryTreeNode(pid);

        List<Object> node = null;

        if (childTreeNodes.size() > 0) {
            node = Lists.newArrayList();

            for (AnimalType animalType : childTreeNodes) {
                if (animalType.getLevel() <= 2) {
                    if (animalType.getParentId() == pid) {
                        Map<String, Object> childArray = Maps.newHashMap();
                        childArray.put("label", animalType.getAnimalName());
                        childArray.put("value", animalType.getAnimalCode());
                        if (animalType.getLevel() == 1) {
                            childArray.put("children", treeNode(animalType.getId()));
                        }


                        node.add(childArray);

                    }
                }


            }
        }
        return node;
    }

    @OpenMethod(
            key = "web.sys.selectAPPRole",
            httpMethods = RequestMethod.GET
    )
    public Response<List> selectAPPRole(){
       List<DicData> list= dicDataService.queryAPPRole();
       List<SysLabelModel> sysLabelModels=new ArrayList<>();
       for (DicData dicData:list){
           if (Integer.parseInt(dicData.getDicValue())<2009){
               SysLabelModel sysLabelModel=new SysLabelModel();
               sysLabelModel.setValue(Integer.valueOf(dicData.getDicValue()));
               sysLabelModel.setLabel(dicData.getDicName());
               sysLabelModels.add(sysLabelModel);
           }

       }

       return Response.ok(sysLabelModels);
    }

    /**
     * 获取三级畜种 (引种记录所需)
     * @param regionAccountId
     * @return
     */
    @OpenMethod(key = "web.farmrecords.queryThirdAnimalType",
            paramNames = {"regionAccountId"},
            httpMethods = RequestMethod.GET)
    public Response<List> queryThirdAnimalType(@RequestParam(required = false) Long regionAccountId){
        try {
            if (animalTypeService == null){
                throw new OPServerException("animalTypeService 为null,请检查");
            }

            List list = null;

            AnimalType animalType = new AnimalType();
            animalType.setRegionAccountId(regionAccountId);
            animalType.setLevel(AnimalTypeEnum.ANIMAL_THIRD_LEVEL.getCode());
            animalType.setStatus(AnimalTypeEnum.ANIMAL_USE.getCode());

            List<AnimalType> animalTypeList = animalTypeService.select(animalType);
            if (animalTypeList != null && animalTypeList.size() > 0){
                list = Lists.newArrayList();
                for (AnimalType animalType1 :animalTypeList){
                    Map map = com.google.common.collect.Maps.newHashMap();
                    map.put("value",animalType1.getAnimalCode());
                    map.put("label",animalType1.getAnimalName());
                    list.add(map);
                }
            }
            return Response.ok(list);
        } catch (Exception e) {
            log.error(e.getMessage());
            throw new OPServerException(HttpCode.INTERNAL_SERVER_ERROR,HttpCode.INTERNAL_SERVER_ERROR.getMessage());
        }
    }

    /**
     * 存栏分析页面的养殖畜种 (猪牛羊家禽)
     */
    @OpenMethod(key = "web.farmrecords.stockAnalysis.obtainStockAnalysisAnimalType",
            paramNames = {},
            httpMethods = RequestMethod.GET)
    public Response<Object> obtainStockAnalysisAnimalType(){
        List<Map> list = Lists.newArrayList();

        List<AnimalType> liveStockAnimalList = null;
        List<AnimalType> oneAnimalTypeList = animalTypeService.queryOneLevel();
        for (AnimalType oneAnimalType : oneAnimalTypeList) {
            if (AnimalTypeEnum.LIVESTOCK.getCode().equals(oneAnimalType.getAnimalCode())){
                liveStockAnimalList = animalTypeService.queryTwoLevel(oneAnimalType.getId());
            } else if (AnimalTypeEnum.POULTRY.getCode().equals(oneAnimalType.getAnimalCode())){
                Map map = Maps.newHashMap();
                //todo  家禽种类
                map.put("value",oneAnimalType.getAnimalCode());
                map.put("label",oneAnimalType.getAnimalName());
                list.add(map);
            }
        }

        //todo 家畜种类
        for (AnimalType animalType : liveStockAnimalList){
            Map child = Maps.newHashMap();
            if (animalType.getAnimalCode() <= AnimalTypeEnum.SHEEP.getCode()){
                child.put("value",animalType.getAnimalCode());
                child.put("label",animalType.getAnimalName());
                list.add(child);
            }
        }

        return Response.ok(list);
    }

    /**
     * 养殖档案获取数据字典表里数据以 (value,label)形式展示
     * @return
     */
    public List<Map> queryDicByGroup(String groupCode){
        try {
            if (dicDataService == null){
                throw new OPServerException("dicDataService 为null,请检查");
            }

            if (Strings.isNullOrEmpty(groupCode)){
                throw new OPServerException(HttpCode.BAD_REQUEST,HttpCode.BAD_REQUEST.getMessage());
            }
            List<DicData> dicDataList = dicDataService.queryDicByGroup(groupCode);
            List list = null;
            if (dicDataList.size() > 0){
                list = Lists.newArrayList();
                for (DicData dicData : dicDataList){
                    Map map = com.google.common.collect.Maps.newHashMap();
                    map.put("value",dicData.getDicValue());
                    map.put("label",dicData.getDicName());
                    list.add(map);
                }
            }
            if (list.size() == 0){
                throw new OPServerException(HttpCode.NOT_FOUND,"查无数据,请检查重试");
            }
            return  list;
        } catch (Exception e) {
            log.error(e.getMessage());
            throw new OPServerException(HttpCode.INTERNAL_SERVER_ERROR,HttpCode.INTERNAL_SERVER_ERROR.getMessage());
        }
    }

    /**
     * 养殖档案获取无害化方式
     * @return
     */
    @OpenMethod(key = "web.farmrecords.obtainHarmlesses",
            paramNames = {},
            httpMethods = RequestMethod.GET)
    public Response<List<Map>> obtainHarmlesses(){
        String key = "FarmRecords:ObtainHarmlesses";
        List list = RedisUtil.getList(key);
        if (list != null && list.size() > 0){
            return Response.ok(list);
        }

        List list1 = this.queryDicByGroup(FarmRecordsDicGroupEnum.HARMLESSES_TYPE.getDicCode());
        if (list1 == null || list1.size() ==0){
            return Response.fail(HttpCode.NOT_FOUND,"查无数据");
        }
        //RedisUtil.setList(key,list1);
        return Response.ok(list1);
    }

    /**
     * 养殖档案获取养殖区域
     */
    @OpenMethod(key = "web.farmrecords.obtainBreedArea",
            paramNames = {},
            httpMethods = RequestMethod.GET)
    public Response<List<Map>> obtainBreedArea(){
        String key = "FarmRecords:ObtainBreedArea";
        List list = RedisUtil.getList(key);
        if (list != null && list.size() > 0){
            return Response.ok(list);
        }

        List list1 = this.queryDicByGroup(FarmRecordsDicGroupEnum.BREED_AREA.getDicCode());
        if (list1 == null || list1.size() ==0){
            return Response.fail(HttpCode.NOT_FOUND,"查无数据");
        }
        //RedisUtil.setList(key,list1);
        return Response.ok(list1);
    }

    /**
     * 养殖档案获取用药方式
     */
    @OpenMethod(key = "web.farmrecords.obtainMedicateMethod",
            paramNames = {},
            httpMethods = RequestMethod.GET)
    public Response<List<Map>> obtainMedicateMethod(){
        String key = "FarmRecords:ObtainMedicateMethod";
        List list = RedisUtil.getList(key);
        if (list != null && list.size() > 0){
            return Response.ok(list);
        }

        List list1 = this.queryDicByGroup(FarmRecordsDicGroupEnum.MEDICATE_METHOD.getDicCode());
        if (list1 == null || list1.size() ==0){
            return Response.fail(HttpCode.NOT_FOUND,"查无数据");
        }
        //RedisUtil.setList(key,list1);
        return Response.ok(list1);
    }

    /**
     * 养殖档案获取原料购置品种
     */
    @OpenMethod(key = "web.farmrecords.obtainMaterialType",
            paramNames = {},
            httpMethods = RequestMethod.GET)
    public Response<List<Map>> obtainMaterialType(){
        String key = "FarmRecords:obtainMaterialType";
        List list = RedisUtil.getList(key);
        if (list != null && list.size() > 0){
            return Response.ok(list);
        }

        List list1 = this.queryDicByGroup(FarmRecordsDicGroupEnum.MATERIAL_TYPE.getDicCode());
        if (list1 == null || list1.size() ==0){
            return Response.fail(HttpCode.NOT_FOUND,"查无数据");
        }
        //RedisUtil.setList(key,list1);
        return Response.ok(list1);
    }

    /**
     * 养殖档案获取饲料种类
     * @return
     */
    @OpenMethod(key = "web.farmrecords.obtainFeedType",
            paramNames = {},
            httpMethods = RequestMethod.GET)
    public Response<List<Map>> obtainFeedType(){
        String key = "FarmRecords:obtainFeedType";
        List list = RedisUtil.getList(key);
        if (list != null && list.size() > 0){
            return Response.ok(list);
        }

        List list1 = this.queryDicByGroup(FarmRecordsDicGroupEnum.FEED_TYPE.getDicCode());
        if (list1 == null || list1.size() ==0){
            return Response.fail(HttpCode.NOT_FOUND,"查无数据");
        }
        //RedisUtil.setList(key,list1);
        return Response.ok(list1);
    }
}
